using FastDevTemplate.Api.Attribute;
using FastDevTemplate.Api.Base;
using FastDevTemplate.Api.Model;
using FastDevTemplate.Api.Model.Base;
using FastDevTemplate.Service;
using FastDevTemplate.Service.Interface;
using FastDevTemplate.Service.Interface.DTO;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace FastDevTemplate.Api.Controllers;

[EnableCors("AllowSpecificOrigin")]
public class CommonController : BaseController
{
    private readonly string? _defaultRoleType;
    private readonly ILogger<UserController> _logger;
    private readonly IUserService _userService;

    public CommonController(IUserService userService, ILogger<UserController> logger, IConfiguration config)
    {
        _userService = userService;
        _logger = logger;
        _defaultRoleType = config["AddUserDefaultRoleType"];
    }

    [HttpPost("login")]
    public async Task<HttpResult<TokenModel>> Login([FromBody] UserLoginModel model)
    {
        if (!ValidateModel(model).isValid)
            return BadResult<TokenModel>();
        var result = await _userService.LoginAsync(model.UserName, model.Password);
        if (result == null)
            return BadResult<TokenModel>();
        var token = TokenService.GenerateToken(result);
        return OkResult(new TokenModel
        {
            Uuid = token.UserLoginDto.ID,
            Token = token.Token,
            RoleKey = token.UserLoginDto.UserRoles.Select(item => item.RoleID).ToList()
        });
    }

    [HttpPost("logout")]
    public HttpResult Logout()
    {
        var uuid = GetUUID();
        if (uuid == null || uuid == Guid.Empty)
            return BadResult();
        var tokenModel = TokenService.TryGetToken(uuid.Value);
        if (tokenModel?.Token != GetToken())
            return BadResult();
        TokenService.RemoveToken(uuid.Value);
        return OkResult();
    }

    [HttpPost("modifyPassword")]
    [PermissionVerification]
    public async Task<HttpResult> UpdatePassword([FromBody] UserUpdatePasswordDto model)
    {
        if (!ValidateModel(model).isValid)
            return BadResult();

        var uuid = GetUUID();
        if (uuid == null || uuid == Guid.Empty)
            return BadResult();
        var tokenModel = TokenService.TryGetToken(uuid.Value);
        if (tokenModel?.Token != GetToken())
            return BadResult();

        var result = await _userService.UpdatePasswordAsync(uuid.Value, model);
        if (result <= 0)
            return BadResult();
        return OkResult();
    }
}